#include "base/log.h"
#include "base/epoll.h"
#include "base/config.h"

#include <memory.h>

#include "base/channel.h"
namespace net_tools::base
{

  Channel::Channel(Epoll *epoll)
      : read_callback_(nullptr),
        write_callback_(nullptr),
        close_callback_(nullptr)
  {
    epoll_type_ = 0;
    event_.events = 0;
    event_.data.ptr = this;
    epoll_ = epoll;
  };
  Channel::~Channel()
  {
    epoll_type_ = 0;
    epoll_->Free_channel(this);
  };
  void Channel::Callback(int epoll_type)
  {
    if ((epoll_type & EPOLLRDHUP) && !(epoll_type & EPOLLIN))
    {
      if (close_callback_)
        close_callback_();
      return;
    }
    if (epoll_type & (EPOLLIN | EPOLLPRI))
    {
      if (read_callback_)
        read_callback_();
      return;
    }
    if (epoll_type & EPOLLOUT)
    {
      if (write_callback_)
        write_callback_();
      return;
    }
  };
  // need already in right thread;
  void Channel::Add_to_epoll()
  {
    epoll_->Add_event(this);
  };
  // need already in right thread;
  void Channel::Mod_to_epoll()
  {
    epoll_->Mod_event(this);
  };
  // need already in right thread;
  void Channel::Del_to_epoll()
  {
    epoll_->Del_event(this);
  };

} // namespace net_tools::base